package com.hbnu.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DatabaseDemo10 {

    //事务的原子性，一个事务中的操作要么都成功要么都失败
    //主要思想是将事务的自动提交改为手动提交
    //此文件为手动提交
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            String url = "jdbc:mysql://localhost:3306/class2211?serverTimezone=UTC&useSSL=false";
            String user = "root";
            String password = "12123";

            connection = DriverManager.getConnection(url,user,password);
            connection.setAutoCommit(false);                //将自动提交改为手动提交

            String sql1 = "update nncc1 set c3=? where c1 = ?";
            preparedStatement =  connection.prepareStatement(sql1);

            preparedStatement.setString(1,"3");             //前面的数字是第几个占位符的意思
            preparedStatement.setString(2,"3");

            int rows = preparedStatement.executeUpdate();

            String sql2 = "update nncc1 set c3=? where c1 = ?";
            preparedStatement =  connection.prepareStatement(sql2);

            preparedStatement.setString(1,"9");                          //注意设置的类型
            preparedStatement.setString(2,"3");
            rows += preparedStatement.executeUpdate();

            connection.commit();                                //手动提交事务
            System.out.println("影响了数据库表"+rows+"条数据");

        } catch (Exception e) {
            //如果事务操作发生异常，需要进行事务回滚

                try {
                    if (connection != null) {
                        connection.rollback();
                    }
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
        }
        finally {
            try {
                if (preparedStatement != null){
                    preparedStatement.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                if (connection != null){
                    connection.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
